package com.mdz.myapplication.utils;

import cn.hutool.crypto.SecureUtil;
import oshi.SystemInfo;
import sun.misc.BASE64Decoder;

import java.io.FileWriter;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {

	/**
	 * &#064;desc:  将字符串转换成RSAPublicKey类型
	 * &#064;date  2020-6-12 11:03:05
	 */
	public static RSAPublicKey getRSAPublidKeyBybase64(String base64s) throws Exception {
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
		RSAPublicKey publicKey = null;
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		try {
			publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return publicKey;
	}

	/**
	 * &#064;desc:  将字符串转换成RSAPrivateKey类型
	 * &#064;date  2020-6-12 11:03:01
	 */
	public static RSAPrivateKey getRSAPrivateKeyBybase64(String base64s) throws Exception{
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
		RSAPrivateKey privateKey = null;
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		try {
			privateKey = (RSAPrivateKey)keyFactory.generatePrivate(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return privateKey;
	}

	public static void savePemFile(Key key, String filename) {
		String encodedKey = Base64.getEncoder().encodeToString(key.getEncoded());
		String keyType = (key instanceof PrivateKey) ? "PRIVATE KEY" : "PUBLIC KEY";
		try (FileWriter writer = new FileWriter(filename)) {
//			writer.write("-----BEGIN " + keyType + "-----\n");
			writer.write(encodedKey);
//			writer.write("\n-----END " + keyType + "-----");
			writer.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	// 辅助方法：从PEM字符串中提取密钥
	public static PrivateKey readPrivateKeyFromPem(String pemKey) throws GeneralSecurityException {
		byte[] keyBytes = Base64.getDecoder().decode(pemKey.replaceAll("\\s+", ""));
		return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
	}

	public static PublicKey readPublicKeyFromPem(String pemKey) throws GeneralSecurityException {
		byte[] keyBytes = Base64.getDecoder().decode(pemKey.replaceAll("\\s+", ""));
		return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes));
	}

//	public static void generatekey(){
////		SystemInfo systemInfo=new SystemInfo();
//////		System.out.println(systemInfo.getHardware().getProcessor().getProcessorIdentifier().getProcessorID());
//////		System.out.println(systemInfo.getHardware().getComputerSystem().getHardwareUUID());
////		String projectPathes = System.getProperty("user.dir") + "/src/main/resources/";
//////		// use hutool's SecureUtil API generate private key, public key
////		KeyPair keyPairs = SecureUtil.generateKeyPair("RSA", 4096, systemInfo.getHardware().getComputerSystem().getHardwareUUID().getBytes());
////		savePemFile(keyPairs.getPrivate(), projectPathes + "/keys/publicKey.pem");
////		savePemFile(keyPairs.getPublic(), projectPathes + "/keys/privateKey.pem");
////	}

	public static void main(String[] args) {
		SystemInfo systemInfo=new SystemInfo();
		String projectPathes = System.getProperty("user.dir") + "/src/main/resources/";
//		// use hutool's SecureUtil API generate private key, public key
		KeyPair keyPairs = SecureUtil.generateKeyPair("RSA", 4096, systemInfo.getHardware().getComputerSystem().getHardwareUUID().getBytes());
		savePemFile(keyPairs.getPrivate(), projectPathes + "/keys/privateKey.pem");
		savePemFile(keyPairs.getPublic(), projectPathes + "/keys/publicKey.pem");
	}
}
